package com.qbm.association.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qbm.association.bean.UserTypeEnum;
import com.qbm.association.entity.Password;
import com.qbm.association.mapper.PasswordMapper;
import com.qbm.association.service.PasswordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.sql.Wrapper;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Aron
 * @since 2022-02-07
 */
@Service
public class PasswordServiceImpl extends ServiceImpl<PasswordMapper, Password> implements PasswordService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private PasswordMapper passwordMapper;

    /**
     * 插入密码信息
     */
    @Override
    public boolean insertUserPassword(Integer userId, UserTypeEnum type, String temp_password) {
        // TODO Auto-generated method stub
        if (userId != null && temp_password != null) {
            String encodePassword = passwordEncoder.encode(temp_password);
            Password password = new Password();
            password.setUserId(userId);
            password.setUserPassword(encodePassword);
            password.setType(type.getCode());
            return 1 == passwordMapper.insert(password);
        }
        return false;
    }

    /**
     * 更改密码
     */
    @Override
    public boolean updateUserPassword(Integer userId,UserTypeEnum type, String password) {
        // TODO Auto-generated method stub
        if (userId != null && password != null) {
            String encodePassword = passwordEncoder.encode(password);
            QueryWrapper<Password> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId).eq("type",type.getCode());
            Password userPassword = passwordMapper.selectOne(queryWrapper);
            userPassword.setUserPassword(encodePassword);
            return 1 == passwordMapper.updateById(userPassword);
        }
        return false;
    }

    @Override
    public boolean matchPassword(Integer userId,UserTypeEnum type, String inputPassword) {
        // TODO Auto-generated method stub
        QueryWrapper<Password> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).eq("type",type.getCode());
        Password password = passwordMapper.selectOne(queryWrapper);
        return passwordEncoder.matches(inputPassword, password.getUserPassword());
    }
}
